<template>
  <div class="advanced-markdown csdn-style">
    <div v-if="showSource" class="source-container">
      <h4>原始Markdown</h4>
      <textarea readonly rows="10" style="width: 100%; padding: 10px; background: #f5f5f5; border: 1px solid #ccc; border-radius: 4px;" v-bind:value="text"></textarea>
    </div>
    
    <!-- 文章目录 -->
    <div v-if="showToc && headingsList.length > 0" class="markdown-toc">
      <div class="toc-title">目录</div>
      <div class="toc-items">
        <div 
          v-for="(heading, index) in headingsList" 
          :key="index"
          class="toc-item"
          :class="`level-${heading.level}`"
          @click="scrollToHeading(heading.id)"
        >
          {{ heading.text }}
        </div>
      </div>
    </div>
    
    <div class="markdown-content">
      <template v-for="part in parsedContent" :key="`part-${part.index}`">
        <div v-if="part.type === 'code'" class="code-block-container">
          <component 
            :is="'CodeHighlighter'"
            :code="part.content"
            :language="part.language"
          ></component>
        </div>
        <div 
          v-else
          v-html="part.content"
          class="markdown-text"
        ></div>
      </template>
    </div>
  </div>
</template>

<script>
import { computed, ref, watch } from 'vue'
import CodeHighlighter from './CodeHighlighter.vue'

export default {
  name: 'AdvancedMarkdown',
  components: {
    CodeHighlighter
  },
  props: {
    text: {
      type: String,
      required: true,
      default: ''
    },
    showSource: {
      type: Boolean,
      default: false
    },
    showToc: {
      type: Boolean,
      default: true
    }
  },
  setup(props) {
    const headingsList = ref([]);
    
    // 生成随机ID
    const generateId = (text) => {
      return 'heading-' + text.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '') + '-' + Math.random().toString(36).substring(2, 6);
    };
    
    // 解析标题，生成目录
    const extractHeadings = (content) => {
      const headings = [];
      const regex = /^(#{1,6})\s+(.+)$/gm;
      let match;
      
      while ((match = regex.exec(content)) !== null) {
        const level = match[1].length;
        const text = match[2].trim();
        const id = generateId(text);
        
        headings.push({
          level,
          text,
          id
        });
      }
      
      return headings;
    };
    
    // 更新目录数据（监听props.text的变化）
    const updateHeadings = () => {
      if (props.text) {
        headingsList.value = extractHeadings(props.text);
      } else {
        headingsList.value = [];
      }
    };
    
    // 初始化目录
    updateHeadings();
    
    // 监听文本变化
    watch(() => props.text, () => {
      updateHeadings();
    });
    
    // 解析Markdown内容，分离代码块和普通文本
    const parsedContent = computed(() => {
      if (!props.text) return [];
      
      const parts = [];
      let remainingText = props.text;
      
      // 查找代码块 ```lang\ncontent```
      const codeBlockRegex = /```([\w-]*)\n([\s\S]*?)```/g;
      let lastIndex = 0;
      let match;
      
      while ((match = codeBlockRegex.exec(remainingText)) !== null) {
        // 添加代码块前的普通文本
        if (match.index > lastIndex) {
          const textBeforeCode = remainingText.substring(lastIndex, match.index);
          if (textBeforeCode.trim()) {
            parts.push({
              type: 'text',
              content: renderSimpleMarkdown(textBeforeCode),
              index: parts.length
            });
          }
        }
        
        // 添加代码块
        parts.push({
          type: 'code',
          language: match[1] || 'plaintext',
          content: match[2].trim(),
          index: parts.length
        });
        
        lastIndex = match.index + match[0].length;
      }
      
      // 添加最后一段文本
      if (lastIndex < remainingText.length) {
        const textAfterLastCode = remainingText.substring(lastIndex);
        if (textAfterLastCode.trim()) {
          parts.push({
            type: 'text',
            content: renderSimpleMarkdown(textAfterLastCode),
            index: parts.length
          });
        }
      }
      
      return parts;
    });
    
    // 简单Markdown渲染(非代码块部分)
    const renderSimpleMarkdown = (text) => {
      // 调试日志，查看处理前文本内容
      
      // 提取所有图片的Markdown标记，将其替换为特殊占位符
      const imageMap = {};
      let imageCounter = 0;
      
      // 预处理文本，将所有图片标记转换为占位符
      let processedText = text.replace(/!\[(.*?)\]\((.*?)\)/g, (match, alt, url) => {
        const placeholderId = `__IMAGE_PLACEHOLDER_${imageCounter}__`;
        imageCounter++;
        
        // 记录图片信息
        imageMap[placeholderId] = { alt: alt || '图片', url: url.trim() };
        
        return placeholderId;
      });
      
      // 处理标题和其他Markdown元素
      processedText = processedText
        .replace(/^# (.+)$/gm, (match, title) => {
          const id = generateId(title);
          return `<h1 id="${id}">${title}</h1>`;
        })
        .replace(/^## (.+)$/gm, (match, title) => {
          const id = generateId(title);
          return `<h2 id="${id}">${title}</h2>`;
        })
        .replace(/^### (.+)$/gm, (match, title) => {
          const id = generateId(title);
          return `<h3 id="${id}">${title}</h3>`;
        })
        .replace(/^#### (.+)$/gm, (match, title) => {
          const id = generateId(title);
          return `<h4 id="${id}">${title}</h4>`;
        })
        // 粗体和斜体
        .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
        .replace(/\*([^*]+)\*/g, '<em>$1</em>')
        // 行内代码
        .replace(/`([^`]+)`/g, '<code>$1</code>')
        // 链接
        .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>')
        // 无序列表
        .replace(/^\s*-\s+(.+)$/gm, '<li>$1</li>')
        .replace(/(<li>.+<\/li>\n)+/g, '<ul>$&</ul>')
        // 有序列表
        .replace(/^\s*\d+\.\s+(.+)$/gm, '<li>$1</li>')
        .replace(/(<li>.+<\/li>\n)+/g, match => {
          if (!/^<ul/.test(match)) {
            return `<ol>${match}</ol>`;
          }
          return match;
        })
        // 换行
        .replace(/\n\n/g, '</p><p>')
        .replace(/\n/g, '<br>');
      
      // 最后处理图片占位符，替换为实际的图片HTML
      Object.keys(imageMap).forEach(placeholder => {
        const { alt, url } = imageMap[placeholder];
        
        // 强制将URL转换为绝对URL
        let absoluteUrl;
        if (url.startsWith('http')) {
          // 已经是完整URL
          absoluteUrl = url;
        } else if (url.startsWith('/')) {
          // 以/开头的相对路径
          absoluteUrl = `http://localhost:5855${url}`;
        } else {
          // 其他相对路径
          absoluteUrl = `http://localhost:5855/${url}`;
        }
        
        
        // 创建图片HTML
        const imgHtml = `<img 
          src="${absoluteUrl}" 
          alt="${alt}" 
          class="markdown-image" 
          style="max-width:100%; height:auto; display:block; margin:15px 0; border-radius:4px; box-shadow:0 2px 8px rgba(0,0,0,0.1);" 
          data-original-url="${url}"
        />`;
        
        
        
        // 替换占位符
        processedText = processedText.replace(placeholder, imgHtml);
      });
      
      return processedText;
    };
    
    // 复制代码
    const copyCode = (code) => {
      navigator.clipboard.writeText(code).then(() => {
        // 可以添加复制成功的提示
        alert('代码已复制到剪贴板');
      }).catch(err => {
        console.error('复制失败:', err);
      });
    };
    
    // 滚动到指定标题
    const scrollToHeading = (id) => {
      const element = document.getElementById(id);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' });
      }
    };
    
    return {
      parsedContent,
      headingsList,
      copyCode,
      scrollToHeading
    };
  }
}
</script>

<style scoped>
.advanced-markdown {
  width: 100%;
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
  color: #333;
  line-height: 1.6;
}

.csdn-style {
  max-width: 1000px;
  margin: 0 auto;
}

.source-container {
  margin-bottom: 20px;
}

/* 目录样式 */
.markdown-toc {
  position: sticky;
  top: 20px;
  float: right;
  width: 250px;
  margin-left: 20px;
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  max-height: 80vh;
  overflow-y: auto;
}

.toc-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.toc-items {
  font-size: 14px;
}

.toc-item {
  padding: 5px 0;
  cursor: pointer;
  color: #666;
  transition: color 0.2s;
}

.toc-item:hover {
  color: #409EFF;
}

.toc-item.level-1 {
  font-weight: 600;
}

.toc-item.level-2 {
  padding-left: 12px;
}

.toc-item.level-3 {
  padding-left: 24px;
  font-size: 13px;
}

.toc-item.level-4 {
  padding-left: 36px;
  font-size: 12px;
}

/* 正文样式 */
.markdown-content {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  overflow: hidden; /* 确保浮动元素不会溢出 */
}

.markdown-text {
  margin-bottom: 16px;
  line-height: 1.8;
}

/* 基本图片样式 */
.markdown-text :deep(img) {
  display: block;
  margin: 15px 0;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  height: auto;
  max-height: 800px; /* 添加最大高度控制 */
  object-fit: contain; /* 确保图片比例正确 */
}

/* 标题样式 */
.markdown-text :deep(h1) {
  font-size: 28px;
  margin-top: 30px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eaecef;
}

.markdown-text :deep(h2) {
  font-size: 24px;
  margin-top: 30px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eaecef;
}

.markdown-text :deep(h3) {
  font-size: 20px;
  margin-top: 24px;
  margin-bottom: 14px;
}

.markdown-text :deep(h4) {
  font-size: 18px;
  margin-top: 24px;
  margin-bottom: 12px;
}

/* 段落样式 */
.markdown-text :deep(p) {
  margin: 16px 0;
  text-indent: 0;
  line-height: 1.8;
}

/* 行内代码样式 */
.markdown-text :deep(code) {
  background-color: rgba(175, 184, 193, 0.2);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  font-size: 0.9em;
}

/* 列表样式 */
.markdown-text :deep(ul), 
.markdown-text :deep(ol) {
  padding-left: 2em;
  margin: 1em 0;
}

.markdown-text :deep(li) {
  line-height: 1.8;
  margin-bottom: 8px;
}

/* 链接样式 */
.markdown-text :deep(a) {
  color: #0366d6;
  text-decoration: none;
}

.markdown-text :deep(a:hover) {
  text-decoration: underline;
}

/* 代码块相关样式 */
.code-block-container {
  margin: 20px 0;
  border-radius: 8px;
  overflow: hidden;
}

.code-block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f6f8fa;
  padding: 8px 16px;
  border-bottom: 1px solid #ddd;
  color: #57606a;
  font-size: 0.85em;
}

.code-language {
  font-family: Consolas, Monaco, monospace;
  text-transform: lowercase;
  color: #57606a;
  font-weight: 600;
}

.code-actions {
  display: flex;
  gap: 12px;
}

.code-copy-btn {
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #eef2f5;
  transition: all 0.2s;
}

.code-copy-btn:hover {
  background-color: #ddd;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .markdown-toc {
    float: none;
    width: 100%;
    margin-left: 0;
    margin-bottom: 20px;
    position: static;
  }
}
</style> 